package com.mimosa.common.view;

import java.util.List;

/**
 * 生成EASYUI的树形数据
 * 
 * @author ggeagle
 * 
 * @param <T>
 */
public abstract class EasyUiTreeData<T> {
	static final String[] COLUMNS = new String[] { "id", "text", "state" };
	/**
	 * 结果列表
	 */
	private List<T> list = null;
	/**
	 * 字符串连接器
	 */
	private StringBuilder builder = new StringBuilder();

	protected EasyUiTreeData(List<T> list) {
		this.list = list;
	}

	/**
	 * 节点的相关描述信息
	 * 
	 * @return
	 */
	protected String[] getColumnNames() {
		return COLUMNS;
	}

	/**
	 * 获取结点的值信息
	 * 
	 * @param t
	 * @return
	 */
	protected abstract String[] getColumnValues(T t);

	/**
	 * 获取属性的名称列表
	 * 
	 * @return
	 */
	protected abstract String[] getColumnAttributeNames();

	/**
	 * 获取属性的值列表
	 * 
	 * @param t
	 * @return
	 */
	protected abstract String[] getColumnAttributeValues(T t);

	/**
	 * 是否生成属性信息
	 * 
	 * @return
	 */
	protected abstract boolean createAttribute();

	void generateDataGrid() {
		this.builder.append("[");
		String[] values = null;
		int index = 0;
		if (this.createAttribute()) {
			for (T t : this.list) {
				this.builder.append("{");
				values = this.getColumnValues(t);
				for (String name : getColumnNames()) {
					this.builder.append("\"").append(name).append("\":\"");
					this.builder.append(values[index++]).append("\",");
				}
				this.builder.append("\"attributes\":{");
				values = this.getColumnAttributeValues(t);
				index = 0;
				for (String name : this.getColumnAttributeNames()) {
					this.builder.append("\"").append(name).append("\":\"");
					this.builder.append(values[index++]).append("\",");
				}
				this.builder.deleteCharAt(this.builder.length() - 1);
				this.builder.append("}},");
				index = 0;
			}
		} else {
			for (T t : this.list) {
				this.builder.append("{");
				values = this.getColumnValues(t);
				for (String name : getColumnNames()) {
					this.builder.append("\"").append(name).append("\":\"");
					this.builder.append(values[index++]).append("\",");
				}
				this.builder.deleteCharAt(this.builder.length() - 1);
				this.builder.append("},");
				index = 0;
			}
		}

		if (this.list.size() > 0) {
			this.builder.deleteCharAt(this.builder.length() - 1);
		}
		this.builder.append("]");
	}

	@Override
	public String toString() {
		if (this.builder.length() < 1) {
			generateDataGrid();
		}
		return this.builder.toString();
	}
}